// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <atomic>
#include <cstdint>
#include <memory>
#include <vector>

#include <pollux/common/base/exceptions.h>
#include <pollux/dwio/common/unit_loader.h>

namespace kumo::pollux::dwio::common::test {

class LoadUnitMock : public LoadUnit {
 public:
  LoadUnitMock(
      uint64_t rowCount,
      uint64_t ioSize,
      std::vector<std::atomic_bool>& unitsLoaded,
      size_t unitId)
      : rowCount_{rowCount},
        ioSize_{ioSize},
        unitsLoaded_{unitsLoaded},
        unitId_{unitId} {}

  ~LoadUnitMock() override = default;

  void load() override {
    POLLUX_CHECK(!isLoaded());
    unitsLoaded_[unitId_] = true;
  }

  void unload() override {
    POLLUX_CHECK(isLoaded());
    unitsLoaded_[unitId_] = false;
  }

  uint64_t getNumRows() override {
    return rowCount_;
  }

  uint64_t getIoSize() override {
    return ioSize_;
  }

  bool isLoaded() const {
    return unitsLoaded_[unitId_];
  }

 private:
  uint64_t rowCount_;
  uint64_t ioSize_;
  std::vector<std::atomic_bool>& unitsLoaded_;
  size_t unitId_;
};

class ReaderMock {
 public:
  ReaderMock(
      std::vector<uint64_t> rowsPerUnit,
      std::vector<uint64_t> ioSizes,
      UnitLoaderFactory& factory,
      uint64_t rowsToSkip);

  bool read(uint64_t maxRows);

  void seek(uint64_t rowNumber);

  std::vector<bool> unitsLoaded() const {
    return {unitsLoaded_.begin(), unitsLoaded_.end()};
  }

 private:
  bool loadUnit();

  std::vector<std::unique_ptr<LoadUnit>> getUnits();

  std::vector<uint64_t> rowsPerUnit_;
  std::vector<uint64_t> ioSizes_;
  std::vector<std::atomic_bool> unitsLoaded_;
  std::unique_ptr<UnitLoader> loader_;
  size_t currentUnit_;
  size_t currentRowInUnit_;
  std::optional<size_t> lastUnitLoaded_;
};

std::vector<std::atomic_bool> getUnitsLoadedWithFalse(size_t count);

} // namespace kumo::pollux::dwio::common::test
